<template>
  <t-button block content="下载" theme="default" @click="handleClick">
    <template #icon>
      <t-icon name="cloud-download" />
    </template>
  </t-button>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { PropType } from 'vue';

import download from '@/utils/download';

// props
const props = defineProps({
  // 接口
  api: {
    type: Function as PropType<(params: { [key: string]: any }) => Promise<any>>,
    required: true,
  },
  // 参数
  params: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({}),
  },
  // 文件类型
  fileType: {
    type: String as PropType<'excel' | 'word' | 'zip' | 'html' | 'markdown'>,
    required: true,
  },
  // 文件名称
  fileName: {
    type: String,
    default: '',
  },
});
// 处理点击
const handleClick = () => {
  props
    .api(props.params)
    .then((data) => {
      MessagePlugin.success('下载成功');
      download[props.fileType](data, props.fileName);
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
</script>
